package org.jctc.els.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

/**
 * 表格输出流
 * @Author
 * @Date 2019/10/18 11:56
 * @Version 1.0
 */
public class FreemarkerUtil {
    public static void contextLoads(HttpServletResponse response,String templateName, String tableName, Map templateDate) throws Exception {
        //1.创建配置类
        Configuration configuration=new Configuration(Configuration.getVersion());
        //2.设置模板所在的目录
        configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/static");
        //3.设置字符集
        configuration.setDefaultEncoding("utf-8");
        //4.加载模板
        Template template=configuration.getTemplate(templateName);
        //设置文件下载的响应头
        response.setContentType("application/json;charset=utf-8");
        //设置文件名
        response.setHeader("Content-Disposition", "attachment;filename="+new String((tableName).getBytes(), "iso-8859-1"));
        //设置模板输出地址为本地
        /*File file = new File("D:\\TM\\");
        if(!file.exists()){
            file.mkdirs();
        }*/
        //Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\TM\\"+tableName),"UTF-8"));
        //设置模板输出地址为网络
        Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8"));
        template.process(templateDate,out);


        //8.关闭Writer对象
        out.flush();
        out.close();

    }

    /*public static String contextLoads(HttpServletResponse response,String templateName, String tableName, Map templateDate) throws Exception {
        //1.创建配置类
        Configuration configuration=new Configuration(Configuration.getVersion());
        //2.设置模板所在的目录
        configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/templates");
        //3.设置字符集
        configuration.setDefaultEncoding("utf-8");
        //4.加载模板
        Template template=configuration.getTemplate(templateName);
        //设置文件下载的响应头
        response.setContentType("application/octet-stream;charset=utf-8");
        //设置文件名
        response.setHeader("Content-Disposition", "attachment;filename="+new String((tableName).getBytes(), "iso-8859-1"));
        //设置模板输出地址为本地
        File file = new File("D:\\TM\\");
        if(!file.exists()){
            file.mkdirs();
        }
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\TM\\"+tableName),"UTF-8"));
        //设置模板输出地址为网络
        //Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8"));


        template.process(templateDate,out);
        System.out.println(template.toString());


        //8.关闭Writer对象
        out.flush();
        out.close();

        return template.toString();

    }*/
}
